package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")

public class CommonController {

    /*
      1、@Value
      2、Environment
      3、配置类 @ConfigurationProperties(prefix = "")
     */

    @Value("${reggie.file-path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file){
        // C:\img  abc.jpg --->  {UUID}.jpg
        String fileName = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));//.jpg
        fileName = fileName+substring;//jaslfdjoiasdfjajdsfoi +  .jpg

        try {
            file.transferTo(new File(path+"\\"+fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传文件失败");
        }

    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //读取磁盘中的文件 IO流
        response.setHeader("Content-Disposition","attachment;filename="+new String(name.getBytes(), "ISO-8859-1"));
        FileInputStream fileInputStream = new FileInputStream(path + File.separator + name);
        IoUtil.copy(fileInputStream,response.getOutputStream());
        fileInputStream.close();
    }
}
